package com.wtf.dsp.admin.interceptor;

import com.wtf.dsp.admin.enums.CommonErrorEnum;
import com.wtf.dsp.admin.exception.WtfDspException;
import com.wtf.dsp.admin.model.LoginUser;
import com.wtf.dsp.admin.service.TokenService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * ClassName: PermissionInterceptor
 * Description: 权限拦截器
 * date: 2024/3/6 18:16
 *
 * @author linhuanyou
 * @version 1.0
 */
@Component
public class PermissionInterceptor extends HandlerInterceptorAdapter {

    @Value("${exec.sql.url:/wtf/exec/mapper/sql}")
    private String execSqlUrl;

    @Value("${exec.sql.signer.key:sskkmklsKKKLSLsslllsopwp9w2okk20kkMD}")
    private String execSqlSignerKey;

    @Value("${exec.sql.signer.header:Wtf-Sql}")
    private String execSqlSignerHeader;

    @Autowired
    private TokenService tokenService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (!(handler instanceof HandlerMethod)) {
            return super.preHandle(request, response, handler);
        }
        //token校验
        String requestURI = request.getRequestURI();
        if(requestURI.equals(execSqlUrl) && StringUtils.isNotBlank(execSqlSignerKey)){
            LoginUser loginUser = tokenService.getLoginUser(request);
            if (loginUser == null)
            {
                String signerVal = request.getHeader(execSqlSignerHeader);
                if(!execSqlSignerKey.equals(signerVal)){
                    throw new WtfDspException(CommonErrorEnum.PERMISSION_DENIED);
                }
            }
        } else {
            LoginUser loginUser = tokenService.getLoginUser(request);
            if (loginUser == null)
            {
                throw new WtfDspException(CommonErrorEnum.ERROR_NOT_LOGIN);
            }
        }
        return super.preHandle(request, response, handler);
    }


    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        AuthContextHolder.getInstance().clear();
    }

}
